# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

import coin.exchange.base.kr_rest.native_public_client_base as npubcb

# Some Notes (2018-Mar-01)
#
# 1. API functionality may be limited by region. Specific products, such as
# market or future, may not be available in every region, specific order
# pairs may be limited to a specific region as well.  The U.S. may only trade
# BTC_USD at this time. European accounts may only trade BTC_EUR at this time.
#
# 2. Please be aware of the HTTP API usage limits below.
#  * The private API is limited to approx. 200 queries per minute
#  * Each IP address is limited to approx. 500 queries per minute
#  * Users who place a large quantity of orders with an amount of 0.01 or
#    less may be temporarily limited to 10 orders per minute.
#  * We may restrict API use if we find that the same order is being
#    repeatedly placed with the intent of placing a heavy load on our system.


class BitflyerNativePublicClient(npubcb.NativePublicClientBase):
  bitflyer_endpoints = {
      "Japan": "https://api.bitflyer.jp/v1/",
      "US": "https://api.bitflyer.com/v1/",
      "Europe": "https://api.bitflyer.com/v1/",
  }

  def __init__(self, timeout=5, region="Japan"):
    url = self.bitflyer_endpoints[region]
    super().__init__(url=url, timeout=timeout)
    self._region = region

  def get_markets(self, region=None):
    region = region or self._region
    assert region in self.bitflyer_endpoints, 'Invalid region.'

    if region == 'Japan':
      url = 'markets'
    elif region == 'US':
      url = 'markets/us'
    elif region == 'Europe':
      url = 'markets/eu'
    else:
      raise ValueError('Invalid region')

    update = self._get_as_json(url)
    return update

  def get_ticker(self, product_code):
    url = 'ticker'
    params = {"product_code": product_code}
    update = self._get_as_json(url, params)
    return update

  def get_exchange_ticker(self):
    # Not documented, found in bitflyer's trading page.
    url = 'https://lightning.bitflyer.com/api/trade/ticker/all?v=1'
    update = self._get_as_json(url)
    return update

  def get_orderbook(self, product_code):
    url = 'board'
    params = {"product_code": product_code}
    update = self._get_as_json(url, params)
    return update

  def get_execution_history(self, product_code):
    url = 'executions'
    params = {"product_code": product_code}
    update = self._get_as_json(url, params)
    return update

  def get_exchange_status(self):
    url = 'gethealth'
    update = self._get_as_json(url)
    return update

  def queryAll(self):
    pass
